package user

import (
	"github.com/gin-gonic/gin"
	"go-base/src/api/request"
	"go-base/src/api/response"
	"go-base/src/core/common"
	"go-base/src/core/middle_ware"
	"go-base/src/logs"
	"go-base/src/model"
	"net/http"
	"strconv"
	"strings"
)

// @Summary 注册单个用户
// @title Swagger Example API
// @version 0.0.1
// @description  register user
// @tags 用户信息
// @Host 127.0.0.1:13333
// @Produce  json
// @Param username query string true "username"
// @Param password query string true "password,需要base64加密"
// @Success 200 {string} json "{"code":200,"data":null,"msg":"ok"}"
// @Router /user/register_user [post]
func RegisterUser(c *gin.Context) {
	paramJson := request.RegisterUser{}
	err := c.ShouldBind(&paramJson)
	if err != nil {
		logs.Error.Printf("参数绑定错误！err:%s\n", err)
		return
	}
	//注册，需要先查询是否存在  存在就登录，不存在注册
	// 是否纯数字
	_, err = strconv.Atoi(paramJson.Username)
	if err == nil {
		logs.Error.Println("用户密码注册失败,用户名是纯数字!")
		response.HttpReturn(c, response.ERR_ALL_NUMBER_REGISTER, err.Error(), "用户密码注册失败,用户名是纯数字!")
		return
	}
	// 是否包含@
	if strings.Contains(paramJson.Username, "@") {
		logs.Error.Println("用户密码注册失败,用户名包含@字符!")
		response.HttpReturn(c, response.ERR_HASE_AT_REGISTER, err.Error(), "用户密码注册失败,用户名包含@字符!")
		return
	}
	// 账号长度
	if len(paramJson.Username) < 0 || len(paramJson.Username) > 50 {
		logs.Error.Println("账号长度不合法")
		response.HttpReturn(c, response.ERR_USERNAME_LENGTH, err.Error(), "账号长度不合法")
		return
	}
	// 密码长度
	if len(paramJson.Password) < 6 || len(paramJson.Password) > 20 {
		logs.Error.Println("密码长度不合法")
		response.HttpReturn(c, response.ERR_PASSWORD_LENGTH, err.Error(), "密码长度不合法")
		return
	}
	user := model.ModelUser{}
	user.Id = common.GenUserUid()
	user.Username = paramJson.Username
	user.Salt, err = middle_ware.Salt()
	if err != nil {
		logs.Error.Printf("盐生成错误！！")
		return
	}
	b, err := middle_ware.IsValidPassword(paramJson.Password)
	if err != nil {
		response.HttpReturn(c, http.StatusBadRequest, gin.H{"password": paramJson.Password}, "错误的密码格式")
		return
	} else {
		if !b {
			logs.Info.Printf("密码 %s 没通过验证\n", paramJson.Password)
			response.HttpReturn(c, http.StatusBadRequest, gin.H{"password": paramJson.Password}, "密码只能是6到20位的字母和数字")
			return
		}
	}
	user.Password = common.EncryptPassword(user.Salt, paramJson.Password)
	err = user.AddUser()
	if err != nil {
		logs.Error.Printf("注册用户失败！！")
		return
	}
	response.StatusOKHttpReturn(c, nil, "ok")
	return
}
